package com.ruoyi.web.controller.biz;

import java.io.*;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.ruoyi.biz.model.req.BizWagesReq;
import com.ruoyi.biz.model.resp.BizWagesResp;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.RoleConstants;
import com.ruoyi.common.utils.SecurityUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.biz.domain.BizWages;
import com.ruoyi.biz.service.BizWagesService;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 工资条Controller
 *
 * @author tianl
 * @date 2025-01-06
 */
@RestController
@RequestMapping("/biz/bizWages")
public class BizWagesController extends BaseController {
    @Autowired
    private BizWagesService bizWagesService;

    /**
     * 工资条全部列表
     */
    @GetMapping(value = "/listAll")
    public AjaxResult listAll(BizWagesReq bizWages) {
        return success(bizWagesService.list(bizWages));
    }

    @GetMapping(value = "/changeAuth")
    public AjaxResult changeAuth() {
        if (SecurityUtils.hasRoles(RoleConstants.ROLE_CEO, RoleConstants.ROLE_FINANCE)) {
            return success(true);
        }
        return success(false);
    }

    /**
     * 查询工资条列表
     */

    @GetMapping("/list")
    public TableDataInfo list(BizWagesReq bizWages) {
        return getDataTable(bizWagesService.listPage(bizWages));
    }

    /**
     * 导出工资条列表
     */

    @Log(title = "工资条", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BizWagesReq bizWages) throws IOException {
        List<BizWagesResp> list = bizWagesService.listExcel(bizWages);
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = System.currentTimeMillis() + "";
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream())
                .withTemplate(RuoYiConfig.getTemplatePath() + "/template.xls").build();
        WriteSheet writeSheet = EasyExcel.writerSheet().build();
        FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
        // 直接写入数据
        excelWriter.fill(list, fillConfig, writeSheet);
        Map<String, Object> map = bizWagesService.sum(list, bizWages.getTime());
        // 写入list之前的数据
        excelWriter.fill(map, writeSheet);
        excelWriter.finish();
    }

    @Anonymous
    @PostMapping("/importExcel")
    public AjaxResult importExcel(@RequestPart("file") MultipartFile file, String time, boolean updateSupport) throws Exception {
        String message = bizWagesService.importExcel(file, time, updateSupport);
        return success(message);
    }

    @Anonymous
    @PostMapping("/download")
    public void download(HttpServletResponse response) throws IOException {
        File descFile = new File(RuoYiConfig.getTemplatePath() + "/download.xls");
        // 输入对象
        FileInputStream fis = new FileInputStream(descFile);
        // 设置相关格式
        response.setContentType("application/force-download");
        // 设置下载后的文件名以及header
        response.addHeader("Content-disposition", "attachment;fileName=download.xls");
        // 创建输出对象
        OutputStream os = response.getOutputStream();
        // 常规操作
        byte[] buf = new byte[1024];
        int len = 0;
        while ((len = fis.read(buf)) != -1) {
            os.write(buf, 0, len);
        }
        fis.close();
    }

    /**
     * 获取工资条详细信息
     */

    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(bizWagesService.selectById(id));
    }

    /**
     * 新增工资条
     */

    @Log(title = "工资条", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BizWages bizWages) {
        bizWagesService.beforeSave(bizWages);
        return AjaxResult.success();
    }

    /**
     * 修改工资条
     */

    @Log(title = "工资条", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BizWages bizWages) {
        bizWagesService.beforeSave(bizWages);
        return AjaxResult.success();
    }

    /**
     * 删除工资条
     */

    @Log(title = "工资条", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(bizWagesService.deleteByIds(ids));
    }
}
